import React from "react";

export interface ColumnDefinition<T> {
  /** The column header title. */
  header: string;
  /**
   * The property key on the data item to display.
   * Optional if a custom render function is provided.
   */
  accessor?: keyof T;
  /**
   * Optional custom render function for the cell.
   * If provided, this function will be used to render the cell.
   */
  render?: (item: T) => React.ReactNode;
}

export interface DataTableProps<T> {
  /** Title for the table (e.g., "Vulnerabilities") */
  title: string;
  /** Array of data items to render in the table */
  data: T[];
  /** Definitions for the columns to display */
  columns: ColumnDefinition<T>[];
}

const DataTable = <T extends {}>({ title, data, columns }: DataTableProps<T>) => {
  return (
    <div className="bg-paper ml-8 mt-4 flex flex-col gap-4 rounded-md border-violet-700/10 p-4 shadow-md shadow-violet-300/10 dark:bg-violet-300/5">
      <h2 className="text-2xl font-extralight">{title}</h2>
      <table className="min-w-full rounded-md bg-gray-800/20">
        <thead>
          <tr className="h-16 w-full border-b border-t-2 border-gray-300 dark:border-gray-600">
            {columns.map((col, index) => (
              <th
                key={index}
                className="pl-4 pr-4 text-left text-sm font-semibold text-gray-600 dark:text-gray-400"
              >
                {col.header}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {data.map((item, rowIndex) => (
            <tr
              key={rowIndex}
              className="h-14 border-b border-gray-300 dark:border-gray-600"
            >
              {columns.map((col, colIndex) => (
                <td key={colIndex} className="pl-4 pr-4 text-sm text-gray-600 dark:text-gray-400">
                  {col.render
                    ? col.render(item)
                    : col.accessor
                    ? (item[col.accessor] as unknown as React.ReactNode)
                    : null}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default DataTable;